package com.zyc.fleamarket.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Date;

/**
 * 发送邮件的工具类
 */
@Component
public class EMailUtils {
    //当前类的实例
    private static EMailUtils INSTANCE = new EMailUtils();

    @Resource
    JavaMailSender mailSender;

    //@PostConstruct  当前对象EMailUtils初始化完成组件注入后，执行后置的处理
    @PostConstruct
    public void init(){
        //给当前类注入属性
        this.INSTANCE.mailSender = mailSender;
    }


    //发送普通邮件的方法
    public static void sendMail(String to,String subject,String contentText){
        SimpleMailMessage message = new SimpleMailMessage();
        //发件人
        message.setFrom("1245439775@qq.com");
        //收件人
        message.setTo(to);
        //主题
        message.setSubject(subject);
        //正文
        message.setText(contentText);
        //发送时间
        message.setSentDate(new Date());
        //执行发送
        INSTANCE.mailSender.send(message);
    }

    //发送多媒体邮件的方法
    public static void sendMIMEMail(String[] to,String subject,String contentText) throws MessagingException, MessagingException {
        //获取多媒体消息对象
        MimeMessage message = INSTANCE.mailSender.createMimeMessage();
        //获取发送邮件的助手
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        //使用助手设置收/发件人/主题/时间/正文
        helper.setFrom("1245439775@qq.com");
        helper.setTo(to);
        helper.setSubject(subject);
        //true表示是否为html格式
        helper.setText(contentText,true);
        //执行发送
        INSTANCE.mailSender.send(message);
    }
}
